/* Copyright (C) 2014-2016 Dan Chapman <dpniel@ubuntu.com>
 * Copyright (C) 2015 Boren Zhang <bobo1993324@gmail.com>

   This file is part of Dekko email client for Ubuntu Devices/

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "OneThreadMsgListModel.h"
#include "3rdParty/trojita/Imap/Model/ThreadingMsgListModel.h"
#include "3rdParty/trojita/Imap/Model/ItemRoles.h"
#include "3rdParty/trojita/Imap/Model/MailboxTree.h"
#include "3rdParty/dovecot/src/lib-imap/imap-base-subject.h"
#include <QDebug>
namespace Dekko
{
namespace Models
{
OneThreadMsgListModel::OneThreadMsgListModel(QObject *parent) :
    QAbstractProxyModel(parent), m_threadRootOffset(-1)
{
    connect(this, &OneThreadMsgListModel::threadRootChanged, this, &OneThreadMsgListModel::dataDidChange);
}

QAbstractItemModel *OneThreadMsgListModel::threadingModel()
{
    return sourceModel();
}

QModelIndex OneThreadMsgListModel::threadRootItem()
{
    if (m_threadRoot.isValid())
        return Imap::deproxifiedIndex(m_threadRoot);
    else
        return QModelIndex();
}

int OneThreadMsgListModel::threadRootItemOffset() const
{
    return m_threadRootOffset;
}

QHash<int, QByteArray> OneThreadMsgListModel::roleNames() const
{
    if (sourceModel()) {
        return sourceModel()->roleNames();
    } else {
        return QHash<int, QByteArray>();
    }
}

QModelIndex OneThreadMsgListModel::index(int row, int column, const QModelIndex &parent) const
{
    return createIndex(row, column, (void *) 0);
}

QModelIndex OneThreadMsgListModel::parent(const QModelIndex &child) const
{
    return QModelIndex();
}

int OneThreadMsgListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!m_threadRoot.isValid()) {
        return 0;
    }
    return sourceModel()->rowCount(m_threadRoot) + 1;
}

int OneThreadMsgListModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QModelIndex OneThreadMsgListModel::mapToSource(const QModelIndex &proxyIndex) const
{
    if (proxyIndex.row() == 0) {
        return m_threadRoot;
    } else {
        return sourceModel()->index(proxyIndex.row() - 1, 0, m_threadRoot);
    }
}

QModelIndex OneThreadMsgListModel::mapFromSource(const QModelIndex &sourceIndex) const
{
    if (!sourceIndex.parent().isValid()) {
        return index(0, 0);
    } else {
        return index(sourceIndex.row() + 1, 0);
    }
}

QVariant OneThreadMsgListModel::data(const QModelIndex &index, int role) const
{
    if (!m_threadRoot.isValid()) {
        return QVariant();
    }
    return QAbstractProxyModel::data(index, role);
}

bool OneThreadMsgListModel::hasValidIndex() const
{
    return m_threadRoot.isValid();
}

int OneThreadMsgListModel::firstInterestingIndex() const
{
    int interestingIndex = -1;
    // because we are a flattened subtree we want
    // source rowCount of m_threadRoot
    for (int idx = 0; idx < rowCount(); ++idx) {
        if (idx == 0) {
            // This is our threadRoot this is special as we already
            // have the data for this one
            // This is the one we will *always* display if there
            // are no older messages still unread.
            interestingIndex = idx;
        } else {
            QModelIndex msg = index(idx, 0);
            if (!msg.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool()) {
                interestingIndex = idx;
            }
        }
    }
    return (rowCount() - interestingIndex) - 1;
}

QString OneThreadMsgListModel::sendersInThread() const
{
    return sourceModel()->data(m_threadRoot, Imap::Mailbox::RoleMessageSendersInThread).toString();
}

QString OneThreadMsgListModel::baseSubject() const
{
    bool isReplyOrForward = (m_threadRoot.data(Imap::Mailbox::RoleMessageIsMarkedReplied).toBool() || m_threadRoot.data(Imap::Mailbox::RoleMessageIsMarkedForwarded).toBool());
    return QString::fromUtf8(
                QByteArray(
                    imap_get_base_subject(
                        m_threadRoot.data(Imap::Mailbox::RoleMessageSubject).toString().toUtf8().data(), &isReplyOrForward)
                    )
                );
}

bool OneThreadMsgListModel::isSubtreeIndex(QModelIndex subtreeIndex) const
{
    if (!m_threadRoot.isValid()) {
        return false;
    }
    while (subtreeIndex.isValid()) {
        if (subtreeIndex == m_threadRoot)
            return true;
        subtreeIndex = subtreeIndex.parent();
    }
    return false;
}

void OneThreadMsgListModel::invalidateModel()
{
    setThreadRootItem(QModelIndex());
}

void OneThreadMsgListModel::markThreadFlagged()
{
    QModelIndexList threadIndexes;
    for (int idx = 0; idx < rowCount(); ++idx) {
        if (idx == 0) {
            // This is our threadRoot this is special as we already
            // have the data for this one
            // This is the one we will *always* display if there
            // are no older messages still unread.
            threadIndexes << Imap::deproxifiedIndex(m_threadRoot);
        } else {
            threadIndexes << Imap::deproxifiedIndex(index(idx, 0));
        }
    }
    const QModelIndex deproxifiedIndex = Imap::deproxifiedIndex(sourceModel()->index(0, 0));
    Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(static_cast<const Imap::Mailbox::Model *>(deproxifiedIndex.model()));
    Q_ASSERT(model);
    if (!model->isNetworkAvailable()) {
        return;
    }
    model->setMessageFlags(threadIndexes, QStringLiteral("\\Flagged"), threadRootFlagged() ? Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD);
}

void OneThreadMsgListModel::markThreadDeleted()
{
    QModelIndexList threadIndexes;
    for (int idx = 0; idx < rowCount(); ++idx) {
        if (idx == 0) {
            // This is our threadRoot this is special as we already
            // have the data for this one
            // This is the one we will *always* display if there
            // are no older messages still unread.
            threadIndexes << Imap::deproxifiedIndex(m_threadRoot);
        } else {
            threadIndexes << Imap::deproxifiedIndex(index(idx, 0));
        }
    }
    const QModelIndex deproxifiedIndex = Imap::deproxifiedIndex(sourceModel()->index(0, 0));
    Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(static_cast<const Imap::Mailbox::Model *>(deproxifiedIndex.model()));
    Q_ASSERT(model);
    if (!model->isNetworkAvailable()) {
        return;
    }
    model->markMessagesDeleted(threadIndexes, m_threadRoot.data(Imap::Mailbox::RoleMessageIsMarkedDeleted).toBool() ?
                                   Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD);
    m_threadRoot = QModelIndex();
    emit threadRootChanged();
}

bool OneThreadMsgListModel::threadRootFlagged() const
{
    return m_threadRoot.data(Imap::Mailbox::RoleMessageIsMarkedFlagged).toBool();
}

void OneThreadMsgListModel::setThreadingModel(QAbstractItemModel *threadingModel)
{
    Imap::Mailbox::ThreadingMsgListModel *model = qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(threadingModel);
    Q_ASSERT(model);
    if (sourceModel() != NULL) {
        disconnect(sourceModel(), 0, this, 0);
    }
    if (model != sourceModel()) {
        setSourceModel(model);
        connect(model, SIGNAL(modelAboutToBeReset()), this, SLOT(handleModelAboutToBeReset()));
        connect(model, SIGNAL(modelReset()), this, SLOT(handleModelReset()));
//        connect(model, SIGNAL(layoutAboutToBeChanged()), this, SIGNAL(layoutAboutToBeChanged()));
//        connect(model, SIGNAL(layoutChanged()), this, SIGNAL(layoutChanged()));
        connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(handleDataChanged(QModelIndex,QModelIndex)));
//        connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SIGNAL(threadCountChanged()));
//        connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(handleRowsAboutToBeRemoved(QModelIndex,int,int)));
//        connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(handleRowsRemoved(QModelIndex,int,int)));
//        connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(handleRowsAboutToBeInserted(QModelIndex,int,int)));
//        connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(handleRowsInserted(QModelIndex,int,int)));
        emit modelsChanged();
    }
}

void OneThreadMsgListModel::setThreadRootItem(QModelIndex rootIndex)
{
    m_threadRoot = rootIndex;
    beginResetModel();
    endResetModel();
    emit threadRootChanged();
}

void OneThreadMsgListModel::setThreadRootItemByOffset(const int row)
{
    if (m_threadRootOffset == row) {
        return;
    }
    m_threadRootOffset = row;
    setThreadRootItem(mapToSource(index(row, 0)));
}

void OneThreadMsgListModel::setOriginalRoot()
{
    setThreadRootItem(QModelIndex());
}

void OneThreadMsgListModel::handleDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
    QModelIndex first = mapFromSource(topLeft);
    QModelIndex last = mapFromSource(bottomRight);

    if (!first.isValid() || !last.isValid()) {
        if (!m_threadRoot.isValid()) {
            emit dataChanged(QModelIndex(), QModelIndex());
            emit dataDidChange();
        } else {
            // No idea how we can even get here??
        }
        return;
    }
    if (first.parent() == last.parent() ) {
        emit dataChanged(first, last);
        emit dataDidChange();
    } else {
        // ignore this as it's either a batched update or
        // an index in the msglist but not in out thread tree
    }
}

void OneThreadMsgListModel::handleModelAboutToBeReset()
{
    beginResetModel();
}

void OneThreadMsgListModel::handleModelReset()
{
    endResetModel();
}

void OneThreadMsgListModel::handleRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
{
    if (!isSubtreeIndex(parent)) {
        return;
    }
    beginRemoveRows(mapFromSource(parent), first, last);
}

void OneThreadMsgListModel::handleRowsRemoved(const QModelIndex &parent, int first, int last)
{
    Q_UNUSED(first);
    Q_UNUSED(last);
    if (!isSubtreeIndex(parent)) {
        return;
    }
    if (!m_threadRoot.isValid()) {
        // Well our thread root disapeared, let's reset the model
        // and just return now
        beginResetModel();
        endResetModel();
        return;
    }
    endRemoveRows();
}

void OneThreadMsgListModel::handleRowsAboutToBeInserted(const QModelIndex &parent, int first, int last)
{
    if (!isSubtreeIndex(parent)) {
        return;
    }
    beginInsertRows(mapFromSource(parent), first, last);
}

void OneThreadMsgListModel::handleRowsInserted(const QModelIndex &parent, int first, int last)
{
    Q_UNUSED(first);
    Q_UNUSED(last);
    if (!isSubtreeIndex(parent)) {
        return;
    }
    endInsertRows();
}
}
}
